package com.bilibili.juc.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zuife
 * @description
 * @since 2024-05-04 08:16:54
 */
public class AtomicIntegerDemo {
    public static final int SIZE = 50;

    public static void main(String[] args) throws InterruptedException {
        MyNumber myNumber = new MyNumber();
        CountDownLatch countDownLatch = new CountDownLatch(SIZE);
        for (int i = 0; i < SIZE; i++) {
            new Thread(() ->
            {
                try {
                    for (int j = 0; j < 1000; j++) {
                        myNumber.addPlusPlus();
                    }
                } finally {
                    countDownLatch.countDown();
                }

            }, String.valueOf(i)).start();
        }
        //等待上面所有线程都执行完，再去获取结果
        countDownLatch.await();

        //暂停几秒，等待上面线程执行完
//        try {
//            TimeUnit.SECONDS.sleep(5);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        System.out.println(Thread.currentThread().getName() + " " + myNumber.get());
    }
}

class MyNumber {
    AtomicInteger atomicInteger = new AtomicInteger();

    public int get() {
        return atomicInteger.get();
    }

    public void addPlusPlus() {
        atomicInteger.getAndIncrement();
    }
}
